<template>
  <div class="activity-list">
    <!-- 搜索和筛选区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索活动名称或描述"
            clearable
            @keyup.enter="handleSearch"
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="活动类型">
          <el-select
            v-model="searchForm.type"
            placeholder="选择活动类型"
            clearable
            style="width: 150px"
          >
            <el-option label="学术类" value="ACADEMIC" />
            <el-option label="文体类" value="CULTURAL" />
            <el-option label="志愿服务" value="VOLUNTEER" />
            <el-option label="社团活动" value="CLUB" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择活动状态"
            clearable
            style="width: 150px"
          >
            <el-option label="报名中" value="registration" />
            <el-option label="即将开始" value="waiting" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="ended" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 活动列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <span class="list-title">
            <el-icon><Calendar /></el-icon>
            活动列表
            <el-tag v-if="total > 0" type="info" size="small">
              共 {{ total }} 个活动
            </el-tag>
          </span>
          <div class="list-actions">
            <el-radio-group v-model="viewMode" size="small">
              <el-radio-button label="card">
                <el-icon><Grid /></el-icon>
                卡片
              </el-radio-button>
              <el-radio-button label="list">
                <el-icon><List /></el-icon>
                列表
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 空状态 -->
      <div v-else-if="activities.length === 0" class="empty-container">
        <el-empty description="暂无活动数据">
          <el-button type="primary" @click="handleReset">
            重新加载
          </el-button>
        </el-empty>
      </div>
      
      <!-- 卡片视图 -->
      <div v-else-if="viewMode === 'card'" class="card-view">
        <el-row :gutter="20">
          <el-col 
            v-for="activity in activities" 
            :key="activity.id"
            :xs="24" 
            :sm="12" 
            :lg="8"
          >
            <div class="activity-card" @click="goToDetail(activity.id)">
              <div class="card-header">
                <h3 class="card-title">{{ activity.title }}</h3>
                <el-tag :type="getActivityStatus(activity).type" size="small">
                  {{ getActivityStatus(activity).text }}
                </el-tag>
              </div>
              
              <div class="card-content">
                <div class="activity-meta">
                  <div class="meta-item">
                    <el-icon><Clock /></el-icon>
                    <span>{{ formatDate(activity.startTime, 'MM-DD HH:mm') }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><Location /></el-icon>
                    <span>{{ activity.location }}</span>
                  </div>
                  <div class="meta-item">
                    <el-icon><User /></el-icon>
                    <span>{{ activity.currentParticipants || 0 }}/{{ activity.maxParticipants || '不限' }}</span>
                  </div>
                </div>
                
                <p class="card-description">{{ activity.description }}</p>
                
                <div class="card-footer">
                  <div class="organizer-info">
                    <span class="organizer-label">组织者：</span>
                    <span class="organizer-name">{{ activity.organizer?.name }}</span>
                  </div>
                  <div class="card-actions">
                    <el-button 
                      type="primary" 
                      size="small"
                      @click.stop="handleRegister(activity)"
                      :disabled="!canRegister(activity)"
                    >
                      {{ getRegisterButtonText(activity) }}
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 列表视图 -->
      <div v-else class="list-view">
        <el-table :data="activities" stripe>
          <el-table-column prop="title" label="活动名称" min-width="200">
            <template #default="{ row }">
              <el-link type="primary" @click="goToDetail(row.id)">
                {{ row.title }}
              </el-link>
            </template>
          </el-table-column>
          
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getActivityTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="startTime" label="开始时间" width="150">
            <template #default="{ row }">
              {{ formatDate(row.startTime, 'MM-DD HH:mm') }}
            </template>
          </el-table-column>
          
          <el-table-column prop="location" label="地点" width="120" />
          
          <el-table-column prop="participants" label="参与人数" width="100">
            <template #default="{ row }">
              {{ row.currentParticipants || 0 }}/{{ row.maxParticipants || '不限' }}
            </template>
          </el-table-column>
          
          <el-table-column prop="organizer" label="组织者" width="120">
            <template #default="{ row }">
              {{ row.organizer?.name }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getActivityStatus(row).type" size="small">
                {{ getActivityStatus(row).text }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small"
                @click="handleRegister(row)"
                :disabled="!canRegister(row)"
              >
                {{ getRegisterButtonText(row) }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { formatDate, getActivityStatus, debounce } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'
import {
  Search,
  Refresh,
  Calendar,
  Grid,
  List,
  Clock,
  Location,
  User
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const viewMode = ref('card')
const activities = ref([])
const total = ref(0)

const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
  dateRange: null
})

const pagination = reactive({
  page: 1,
  size: 12
})

// 已报名的活动ID集合
const registeredActivityIds = ref(new Set())

const getActivityTypeText = (type) => {
  const typeMap = {
    ACADEMIC: '学术类',
    CULTURAL: '文体类',
    VOLUNTEER: '志愿服务',
    CLUB: '社团活动',
    OTHER: '其他'
  }
  return typeMap[type] || type
}

const canRegister = (activity) => {
  const status = getActivityStatus(activity)
  return status.status === 'registration' && !registeredActivityIds.value.has(activity.id)
}

const getRegisterButtonText = (activity) => {
  if (registeredActivityIds.value.has(activity.id)) {
    return '已报名'
  }
  
  const status = getActivityStatus(activity)
  switch (status.status) {
    case 'registration':
      return '立即报名'
    case 'waiting':
      return '报名已截止'
    case 'ongoing':
      return '进行中'
    case 'ended':
      return '已结束'
    default:
      return '查看详情'
  }
}

const loadActivities = async () => {
  try {
    loading.value = true
    
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    
    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    const response = await api.get('/activities', { params })
    const { data, total: totalCount } = response.data.data
    
    activities.value = data || []
    total.value = totalCount || 0
    
  } catch (error) {
    console.error('加载活动列表失败:', error)
    ElMessage.error('加载活动列表失败')
  } finally {
    loading.value = false
  }
}

const loadRegisteredActivities = async () => {
  try {
    const response = await api.get('/registrations/my-activities')
    const registeredIds = response.data.data?.map(item => item.activityId) || []
    registeredActivityIds.value = new Set(registeredIds)
  } catch (error) {
    console.error('加载已报名活动失败:', error)
  }
}

const handleSearch = debounce(() => {
  pagination.page = 1
  loadActivities()
}, 300)

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    status: '',
    dateRange: null
  })
  pagination.page = 1
  loadActivities()
}

const handlePageChange = (page) => {
  pagination.page = page
  loadActivities()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadActivities()
}

const goToDetail = (activityId) => {
  router.push(`/student/activities/${activityId}`)
}

const handleRegister = async (activity) => {
  if (!canRegister(activity)) {
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要报名参加「${activity.title}」吗？`,
      '确认报名',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    await api.post('/registrations', {
      activityId: activity.id
    })
    
    ElMessage.success('报名成功，请等待审核')
    registeredActivityIds.value.add(activity.id)
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('报名失败:', error)
      ElMessage.error(error.message || '报名失败')
    }
  }
}

onMounted(() => {
  loadActivities()
  loadRegisteredActivities()
})
</script>

<style scoped>
.activity-list {
  max-width: 1200px;
  margin: 0 auto;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.list-card {
  min-height: 600px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.list-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.loading-container,
.empty-container {
  padding: 40px 20px;
  text-align: center;
}

/* 卡片视图 */
.card-view {
  margin-bottom: 20px;
}

.activity-card {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.activity-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
  margin-right: 12px;
  line-height: 1.4;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.activity-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.card-description {
  color: #909399;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 16px 0;
  flex: 1;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.organizer-info {
  font-size: 14px;
}

.organizer-label {
  color: #909399;
}

.organizer-name {
  color: #606266;
  font-weight: 500;
}

.card-actions {
  display: flex;
  gap: 8px;
}

/* 列表视图 */
.list-view {
  margin-bottom: 20px;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
  
  .list-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .activity-meta {
    flex-direction: column;
    gap: 8px;
  }
  
  .card-footer {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .list-view {
    overflow-x: auto;
  }
}
</style>